// $Id: script.js 353 2012-12-03 04:54:09Z bobcat $
// This file contains scripts to be run on every page. Mainly cookie and API
// initialization, plus definitions of some useful utility functions.

// Namespace our global functions using this object.
var DSC = {};

/*
 * Gets a good page to redirect to. We don't want to redirect to odd pages like
 * login/logout, etc., so I check for a few weird ones.
 *
 * @param stripParams - some parameters are problematic, especially when on
 * the UltraCart generated pages (checkout). Set this to true to change the
 * parameters as necessary.
 */
DSC.getReferrer = function(stripParams) {
  var ref = document.referrer,
      exp = /(^$)|(log(out|in))|(activate)/gi; // (empty) or (contains: (logout) or (login))
  if (stripParams) {
    ref = ref.replace(/html5\=true/, '');
    ref = ref.replace(/HTML5/, 'DSC');
  }
  return (exp.test(ref)) ? '/' : ref;
};

/*
 * Create a cookie on the user's browser.
 *
 * @param name - name of the cookie.
 * @param value - value of the cookie.
 * @param days - how long the cookie should last.
 */
DSC.createCookie = function(name, value, days) {
  var date,
      expires;
  if (days) {
    date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = '; expires=' + date.toGMTString();
  } else {
    expires = '';
  }
  document.cookie = name + '=' + value + expires + '; path=/';
}

/*
 * Read the value of a cookie. Returns null if not found.
 *
 * @param name - the name of the cookie.
 */
DSC.readCookie = function(name) {
  var nameEQ = name + '=',
      ca = document.cookie.split(';'),
      len = ca.length,
      i,
      c;
  for(i = 0; i < len; i += 1) {
    c = ca[i].replace(/^\s+/, '');
    if (c.indexOf(nameEQ) === 0) {
      return c.substring(nameEQ.length, c.length);
    }
  }
  return null;
}

/*
 * Erases a cookie from the user's browser.
 *
 * @param name - the name of the cookie.
 */
DSC.eraseCookie = function(name) {
  DSC.createCookie(name,"",-1);
}

/*
 * Redirect the user after a specified delay.
 *
 * @param ref - the URI to redirect to.
 * @param ms - the delay in milliseconds unti redirect.
 */
DSC.redirectAfter = function (ref, ms) {
  setTimeout(function() {
    window.location = ref;
  }, ms);
};

DSC.preloadImages = function() {
  var i, len, img;
  for (i = 0, len = arguments.length; i < len; i += 1) {
    img = new Image();
    img.src = arguments[i];
  }
};

/*
 * Common behavior to be run on page load.
 */
$(document).ready(function() {
  // Sometimes Velocity templates won't be executed if they have been
  // nested too far. Usually a refresh of the page forces a re-execution.
  // So here I check to see if any of the notorious product templates haven't
  // been rendered and force a refresh. Sucks, but it only has to happen once
  // per page in the catalog.
  if ($('.tab:contains("#tech"), .tab:contains("#discounts"), .tab:contains("#crossref"), .tab:contains("#apps")').length > 0) {
    window.location = window.location;
  }

  // Initialize the UltraCart JavaScript API
  ultraCart.init({
    merchantId: 'TMCSC',
    screenBrandingThemeCode: 'HTML5',
    checkoutSite: 'www.datastoragecables.com',
    remoteApiUrl: location.protocol + '//' + location.hostname + '/cgi-bin/UCCheckoutAPIJSON'
  })

  // Clicking on a navigation item will toggle its sublist. If a user doesn't
  // have JavaScript, the list will show on hover instantly, and a click will
  // take that user to the group page. But here we don't follow the anchor, and
  // the sublist is shown with a quick animation.
//  $('nav.drop > ul > li > a').toggle(
//    function() {
//      var $this = $(this);
//      $this.addClass('active');
//      $this.siblings('ul:first').slideDown('fast');
//      return false; // prevent following the anchor
//    },
//    function() {
//      var $this = $(this);
//      $this.siblings('ul:first').slideUp('fast', function() {
//        $this.removeClass('active');
//      });
//      return false; // prevent following the anchor
//    }
//  );

  $('nav.drop > ul > li > a[href="' + location.protocol + '//' + location.hostname + location.pathname + '"]').addClass('active').siblings('ul:first').slideDown('fast');

//    $('nav.drop > ul > li > a').mouseover(function(){
//
//        var $this = $(this);
//
//        if ($this.attr('class') == 'active') {
//            $this.siblings('ul:first').slideUp(1000, function() {
//                $this.removeClass('active');
//            });
//            return false; // prevent following the anchor
//        } else {
//            $this.addClass('active');
//            $this.siblings('ul:first').slideDown(1000);
//            return false; // prevent following the anchor
//        }
//    });
//    $('nav.drop > ul > li > a').onmouseout(function(){});


    
  // This might be able to go away now. It was to allow switching from the HTML4
  // version of the site to the HTML5 version. Essentially, it just tacks on a
  // query parameter to all links if a given cookie is set.
  (function(cookie, paramString) {
    // if cookie is set to true, add paramString
    // to all hrefs and actions
    if (DSC.readCookie(cookie)) {
      $('body *[href]').each(function() {
        $(this).attr('href', $(this).attr('href') + paramString);
      });
      $('body *[action]').each(function() {
        $(this).attr('action', $(this).attr('action') + paramString);
      });
    }
  })('html4', '?html4=true');
});